package com.soulmate.order.service;

import com.soulmate.api.stock.StockService;
import com.soulmate.exception.BusinessException;
import com.soulmate.order.api.OrderService;
import com.soulmate.order.dao.OrderDao;
import com.soulmate.order.data.OrderDO;
import com.soulmate.order.dto.OrderDTO;
import com.soulmate.prudoct.api.ProductService;
import com.soulmate.prudoct.dto.ProductDTO;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.Objects;

/**
 * @author huaiping
 * @date 2/20/23-2:38 PM
 */
@Slf4j
@DubboService
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao;

    @DubboReference
    private ProductService productService;
    @DubboReference
    private StockService stockService;

    @Override
    public OrderDTO getOrderById(String orderId) {
        return toDTO(orderDao.selectById(orderId));
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public OrderDTO createOrder(OrderDTO orderDTO) throws BusinessException {
        // 判断商品是否存在
        ProductDTO product = productService.getProductById(orderDTO.getProductId());
        if (Objects.isNull(product)) {
            log.error("创建订单失败，商品:{} 不存在", orderDTO.getProductId());
            throw new BusinessException(String.format("商品: %s 不存在", orderDTO.getProductId()), 404);
        }
        // 扣除库存
        stockService.deduct(orderDTO.getProductId(), orderDTO.getProductQuantity());
        OrderDO orderDO = toDO(orderDTO);
        orderDao.insert(orderDO);
        orderDTO.setId(orderDO.getId());
        System.out.println(1/0);
        return toDTO(orderDO);
    }

    private OrderDTO toDTO(OrderDO orderDO) {
        return OrderDTO.builder()
                .id(orderDO.getId())
                .productId(orderDO.getProductId())
                .orderAmount(orderDO.getOrderAmount())
                .productQuantity(orderDO.getProductQuantity())
                .createUser(orderDO.getCreateUser())
                .createTime(orderDO.getCreateTime())
                .build();
    }

    private OrderDO toDO(OrderDTO orderDTO) {
        return OrderDO.builder()
                .id(orderDTO.getId())
                .productId(orderDTO.getProductId())
                .orderAmount(orderDTO.getOrderAmount())
                .productQuantity(orderDTO.getProductQuantity())
                .createUser(orderDTO.getCreateUser())
                .createTime(orderDTO.getCreateTime())
                .build();
    }
}
